package com.kyb.cms.config;

import com.kyb.cms.config.interceptor.LoginStatusInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.armada.galileo.mvc_plus.converter.String2BigDecimalConverter;
import org.armada.galileo.mvc_plus.converter.String2DoubleConverter;
import org.armada.galileo.mvc_plus.converter.String2IntegerConverter;
import org.armada.galileo.mvc_plus.converter.String2LongConverter;
import org.armada.galileo.mvc_plus.support.MiniWebxServlet;
import org.armada.galileo.rainbow_gate.transfer.discovery.LocalServerAddressUtil;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.support.FormattingConversionServiceFactoryBean;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * nova 系列中间件引用
 *
 * @author xiaobo
 * @date 2021/11/1 6:46 下午
 */
@Slf4j
public class SuperMiniwebxConfig {

    static {
        System.setProperty("localIp", LocalServerAddressUtil.getLocalServerIp());
    }

    public static FormattingConversionServiceFactoryBean initMiniwebxConversion() {
        FormattingConversionServiceFactoryBean conversion = new FormattingConversionServiceFactoryBean();
        Set<Converter<?, ?>> converters = new HashSet<Converter<?, ?>>();
        converters.add(new String2DoubleConverter());
        converters.add(new String2IntegerConverter());
        converters.add(new String2BigDecimalConverter());
        converters.add(new String2LongConverter());
        conversion.setConverters(converters);
        return conversion;
    }

    public static ServletRegistrationBean initMiniwebx(ApplicationContext applicationContext, String contextPath, String modulePath) {

        String innerAppName = contextPath;
        if (contextPath.indexOf("-") != -1) {
            innerAppName = contextPath.substring(0, contextPath.indexOf("-"));
        }

        System.setProperty("bronzeAppName", innerAppName);

        List<HandlerInterceptor> interceptors = new ArrayList<>();

//        interceptors.add(new TraceIdInterceptor());
        interceptors.add(new LoginStatusInterceptor());
//        interceptors.add(new PagingInterceptor());
//        interceptors.add(new I18nSpringInterceptor());

        MiniWebxServlet servlet = new MiniWebxServlet(modulePath, contextPath, applicationContext, interceptors);
        return new ServletRegistrationBean<MiniWebxServlet>(servlet, "/", "*.json", "*.htm", "/statics/*");
    }

}
